<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <tree-table
        class="treeTable"
        :data="CateList"
        :columns="columns"
        show-index
        border
        :expand-type="false"
        :selection-type="false"
      >
        <template slot="isok" slot-scope="scope">
          <i class="el-icon-success" v-if="scope.row.cat_deleted===false" style="color:lightgreen"></i>
          <i class="el-icon-error" v-else style="color:red"></i>
        </template>
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0" size="mini">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1" size="mini">二级</el-tag>
          <el-tag type="warning" v-else-if="scope.row.cat_level === 2" size="mini">三级</el-tag>
          <el-tag type="danger" v-else>其他</el-tag>
        </template>
        <template slot="opt" slot-scope='scope'>
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.cat_id)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id,scope.row.cat_name)">删除</el-button>
        </template>
      </tree-table>

      <!-- 分页部分 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[3, 5, 10, 15]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类窗口 -->
    <el-dialog title="添加商品分类" :visible.sync="addDialogVisible" width="50%" @close="addCateClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="Cascadervalue"
            :options="ParentCateList"
            :props="CascaderProps"
            @change="CascaderChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>


    <!-- 修改分类窗口 -->
    <el-dialog title="修改商品分类" :visible.sync="editDialogVisible" width="50%" @close="editCloseHandle">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      CateList: [],
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0
      },
      editForm: {
      },
      addFormRules: {
        cat_name: {
          required: true,
          message: "分类名称不能为空",
          trigger: "blur"
        }
      },
      editFormRules: {
        cat_name: {
          required: true,
          message: "分类名称不能为空",
          trigger: "blur"
        }
      },
      ParentCateList: [],
      CascaderProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
        checkStrictly: true
      },
      Cascadervalue: [],
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "isok",
          prop: "cat_deleted"
        },
        {
          label: "排序",
          type: "template",
          template: "order",
          prop: "cat_level"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ]
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.querInfo
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        // console.log(res.data);
        this.CateList = res.data.result;
        this.total = res.data.total;
      }
    },
    handleSizeChange(newSize) {
      this.querInfo.pagesize = newSize;
      this.getCateList();
    },
    handleCurrentChange(newPage) {
      this.querInfo.pagenum = newPage;
      this.getCateList();
    },
    showAddCateDialog() {
      this.addDialogVisible = true;
      this.getParentCateList();
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        // console.log(res);
        this.ParentCateList = res.data;
        // console.log(this.ParentCateList);
      }
    },
    CascaderChange() {
      // console.log(this.Cascadervalue);
      if (this.Cascadervalue.length > 0) {
        this.addForm.cat_pid = this.Cascadervalue[
          this.Cascadervalue.length - 1
        ];
        this.addForm.cat_level = this.Cascadervalue.length;
      } else {
        this.addForm.cat_pid = 0;
        this.addForm.cat_level = 0;
      }
    },
    addCate() {
      // console.log(this.addForm);
      this.$refs.addFormRef.validate(async valide => {
        if (!valide) {
          return this.$message.error("未通过表单验证！");
        } else {
          const { data: res } = await this.$http.post(
            "categories",
            this.addForm
          );
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.addDialogVisible = false;
            this.getCateList();
          }
        }
      });
    },
    addCateClosed() {
      this.$refs.addFormRef.resetFields();
      this.addForm.cat_level = 0;
      this.addForm.cat_pid = 0;
      this.Cascadervalue = [];
    },
    editCloseHandle(){
      this.$refs.editFormRef.resetFields();
    },
    async showEditDialog(id){
      const { data: res } = await this.$http.get("categories/" + id);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg);
      } else {
        this.editForm = res.data;
        this.editDialogVisible = true;
      }
    },
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error("表单内容格式不正确！");
        } else {
          const { data: res } = await this.$http.put(
            "categories/" + this.editForm.cat_id,
            { cat_name: this.editForm.cat_name}
          );
          console.log(this.editForm);
          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg);
          } else {
            this.$message.success(res.meta.msg);
            this.editDialogVisible = false;
            this.getCateList();
          }
        }
      });
    },
    async deleteCate(id,name){
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      } else {
        const { data: res } = await this.$http.delete("categories/" + id);
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg + "删除失败");
        } else {
          this.$message.success("商品分类" + name + "已被删除成功!");
          this.getCateList();
        }
      }
    }
  }
};
</script>
<style lang="less" scoped>
.treeTable {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>